//获取应用实例
let app = getApp();
let FormCheckRule = {
	telRule: /^[1]{1}[0-9]{10}$/,	
	nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
	carNullMessage: '请选择可延期车辆',
	nameNullMessage: '请输入收件人姓名',
	nameErrorMessage: '请输入正确的收件人姓名',
	phoneNullMessage: '请输入手机号码',
	phoneErrorMessage: '请输入正确的手机号码',
	areaNullMessage: '请选择所在地区',
	streetNullMessage: '请输入详细地址',
	streetErrorMessage: '请输入正确的详细地址'
}

Page({
    data: {
		isCanScroll: true, //屏幕是否能够滑动
		tagData: [
			{text: '可延期车辆',index: 1},
			{text: '不可延期车辆',index: 2}
		],

		payMentTypeData: [   //取证方式
			{times: 2, timesName: "邮政速递",},
			{times: 1, timesName: "前台领取"}
		],
		directTitle: '', //办理的类型 1 专业 2 业余
		fileNbr: '', //办理的内容
		
		payMentType: '2', //领取方式
		payMentTypeName: '邮政速递',
		canUseList: [], //可预期三条数据
		canUseListAdd: [], //三条后所有数据

		noUseList: [], //不可预期三条数据
		noUseListAdd: [], //三条后所有数据
		
		isShowAddMore: false, //可延期车辆点击加载更多按钮显示
		isShowAddMoreMustNot: false, //不可延期车辆点击更多按钮显示
		checkedAll: false, //全部勾选
		addMore: false, //是否点击更多内容
		isShowAddMoreMustNot: false, //是否点击更多内容
		tagAction: 1, //顶部导航默认选项
		name: '', //收件人姓名
		phone: '', //号码
		street: '', //详细地址
		address: {}, //收件地址
		fullAddr: '', //地址的全拼
		area: '' //详细地址
	},

	save() {
		let selectData = [], //选择上的数据
			{ directType, inlandTelNbr, payMentType,
				fileNbr, witnessName, cardNbr, 
				carArchivesNbr, inlandCarNbr, frameLastSix, canUseList, canUseListAdd,
				address, street, area, name, phone ,
				nameIconType, phoneIconType, streetIconType} = this.data;
		let canUseListAll = [...canUseList, ...canUseListAdd]; //...canUseListAdd
		console.log(canUseListAll)
		for (let i = 0; i < canUseListAll.length; i++) {
			if (canUseListAll[i].check) {
				selectData.push(canUseListAll[i])
			}
		}

		let n = []; //一个新的临时数组 
		//遍历当前数组 
		for (let j = 0; j < selectData.length; j++) { 
			if (n.indexOf(selectData[j]) == -1) n.push(selectData[j]); 
		} 
		selectData =  n; 

		console.log(address)
		console.log('this.data',this.data)
		console.log('可预期的车辆',selectData)

		if (payMentType == 1) {
			let flag = app.check([
				{
					value: selectData.length, //选择的可延期车辆
					errorFocusName: '',
					errorScrollIntoViewName: 'topPayMent',
					fn: (value) => {
						console.log(value)
						if (!value) { 
							app.errorToast(FormCheckRule.carNullMessage);
							return false;
						} else {
							return true;
						}
					}
				}
			]);
			if (!flag) {
				return false;
			}	
		} else if (payMentType == 2) {
			let flag = app.check([
				{
					value: selectData.length, //选择的可延期车辆
					errorFocusName: '',
					errorScrollIntoViewName: 'topPayMent',
					fn: (value) => {
						console.log(value)
						if (!value) { 
							app.errorToast(FormCheckRule.carNullMessage);
							return false;
						} else {
							return true;
						}
					}
				}, {
					value: name, //收件人姓名
					errorFocusName: 'name',
					errorScrollIntoViewName: 'addressSign',
					fn: (value) => {
						if (value == '') { 
							app.errorToast(FormCheckRule.nameNullMessage);
							return false;
						} else if (nameIconType == 'error') {
							app.errorToast(FormCheckRule.nameErrorMessage);
							return false;
						} else {
							return true;
						}
					}
				}, {
					value: phone, //手机号码
					errorFocusName: 'phone',
					errorScrollIntoViewName: 'addressSign',
					fn: (value) => {
						if (value == '') { 
							app.errorToast(FormCheckRule.phoneNullMessage);
							return false;
						} else if (phoneIconType == 'error') {
							app.errorToast(FormCheckRule.phoneErrorMessage);
							return false;
						} else {
							return true;
						}
					}
				}, {
					value: area, //选择地址
					errorFocusName: '',
					errorScrollIntoViewName: 'addressSign',
					fn: (value) => {
						if (value == '') { 
							app.errorToast(FormCheckRule.areaNullMessage);
							return false;
						} else {
							return true;
						}
					}
				}, {
					value: street, //详细地址
					errorFocusName: 'street',
					errorScrollIntoViewName: 'addressSign',
					fn: (value) => {
						if (value == '') { 
							app.errorToast(FormCheckRule.streetNullMessage);
							return false;
						} else if (streetIconType == 'error') {
							app.errorToast(FormCheckRule.streetErrorMessage);
							return false;
						}else {
							return true;
						}
					}
				}
			]);			
			if (!flag) {
				return false;
			}	
		}

		let that = this;
		//领证方式directType  1/前台办理 2/邮证速递
		let postData = {
			//附属信息
			inlandTelNbr: inlandTelNbr, //内地手机号码
			directType: directType,  //1 专业 2 非专业
			licensingWay: payMentType, //1 上门 2 邮寄领证方式
			info: JSON.stringify(selectData) //勾选的选项
		}
		if (payMentType == 2) {
			postData['address.contactName'] = name
			postData['address.cellNum'] = phone
			postData['address.street'] = street
			postData['address.area'] = area
			postData['address.fullAddr'] = area + street //全拼地址
			postData['address.provinceId'] = address.provinceId
			postData['address.cityId'] = address.cityId
			postData['address.countyId'] = address.countyId
			postData['address.provinceName'] = address.provinceName
			postData['address.cityName'] = address.cityName
			postData['address.countyName'] = address.countyName
		}
		
		if (directType == 1) {
			postData['fileNbr'] = fileNbr	
			postData['cardNbr'] = cardNbr //"4401111"	
			postData['witnessName']	= witnessName//"张三"
		} else if (directType == 2) {
			postData['fileNbr'] = fileNbr	
			postData['carArchivesNbr'] = carArchivesNbr 
			postData['inlandCarNbr'] = inlandCarNbr        //"sdf"	
			postData['frameLastSix'] = frameLastSix       //"456456"
		}
		let opt = {
			url: app.globalData.host+"/wx/hkmdc/handling.ajax",
			data: postData,
			sucFn: (result) => {				
				console.log(result.body)
				app.setStorageSync(app.globalData.cacheConfirem, Object.assign({}, postData, {payType: result.body.payType} ,{'money': JSON.stringify(result.body)}));
				app.navigateTo({url:'../payment/payment'})
			}
		};
		app.ajax(opt);
	},

	//输入框公用方法
    infoInput(e) {
        let id = e.currentTarget.id,
			value = e.detail.value.replace(/(^\s*)|(\s*$)/g,"");
		//非专业车辆
		if (id == 'name') {
			this.setData({name: value});
            if( value.length == '') {
                this.setData({nameIconType: "success"});
            } else if(FormCheckRule.nameRule.test(value)) {
                this.setData({nameIconType: "success"});
            } else if(value.length>0){
                this.setData({nameIconType: "error"});
            }else{
                this.setData({nameIconType: ""});
            }
		} else if(id == "phone") { //内地手机号码
            value = value.substr(0, 11);
            this.setData({phone: value});
            if(value==''){
                this.setData({phoneIconType: "success"});
            }else if (FormCheckRule.telRule.test(value)) {
                this.setData({phoneIconType: "success"});
            } else if (value.length > 0) {
                this.setData({phoneIconType: "error"});
            } else {
                this.setData({phoneIconType: ""});
            }
        } else if(id == "street") { //详细信息
			this.setData({street: value});
			if (value==''||value.length>4) {
				this.setData({streetIconType: "success"});
			} else if(value.length>0) {
				this.setData({streetIconType: "error"})
			} else {
				this.setData({streetIconType: ""})
			}
		}
	},
	//点击邮寄类型显示类别列表
	payMentTypeSelection(e) {
		this.setData({
			isCanScroll:false,
			isShowSendTypeList: true,
			isShowFootNav: false
		});
	},

  //点击mask隐藏旅游邮寄类别列表
	hideSendTypeSelection() {
		this.setData({
			isCanScroll: true,
			isShowSendTypeList: false,
			isShowFootNav: true
		});
	},

	//选择邮寄类型
	selectPayMentType(e) {
		this.setData({
			payMentType: e.target.dataset.type,
			payMentTypeName: e.target.dataset.name
		})
	},

	/**** 地址 start ****/
	// 显示区域选择框
    showAddressPicker() {
        this.setData({
            isShow: true,
        })
    },
    // 隐藏区域选择框
    cancelAddressTap() {
        this.setData({
            isShow: false,
        })
    },

    //选择城市确定按钮
    confirmAddressTap(e) {
        console.log(this.data.value);
        let current_value = this.data.value,
			provinceName = this.data.proviceData[current_value[0]].name,
			cityName = this.data.cityData[current_value[1]].name,
			countyName = "";
        if (this.data.districtData[current_value[2]].name != null) {
            countyName = this.data.districtData[current_value[2]].name;
        }

        this.setData({
            isShowFootNav: true,
            isAddressShow: false,
            areaStyle: "color:#1a1a1a;font-size:32rpx",
            area: provinceName + cityName + countyName,
			"address.provinceId":this.data.proviceData[current_value[0]].id,
			"address.cityId":this.data.cityData[current_value[1]].id,
			"address.countyId":this.data.districtData[current_value[2]].id,
			"address.provinceName":provinceName,
			"address.cityName":cityName,
			"address.countyName":countyName
		});
    },
    //省市区滑动事件
    bindAddressChange(e) {
        app.bindAddressChange(e);
	},
	
	/**** 地址 end ****/

	// 切换更多或收起
	addMore() {
		let { tagAction } = this.data;
		if (tagAction == 1) {
			if (!this.data.addMore) {
				this.setData({
					canUseList: [...this.data.canUseList, ...this.data.canUseListAdd]
				})
			} else {
				this.setData({
					canUseList: this.data.canUseList.slice(0,3)
				})
			}
			this.setData({
				addMore: !this.data.addMore
			})
		} else {
			if (!this.data.addMoreMustNot) {
				this.setData({
					noUseList: [...this.data.noUseList, ...this.data.noUseListAdd]
				})
			} else {
				this.setData({
					noUseList: this.data.noUseList.slice(0,3)
				})
			}
			this.setData({
				addMoreMustNot: !this.data.addMoreMustNot
			})
		}
	},
	//全选
	checkedAll() {
		let canUseList = this.data.canUseList;
		let canUseListAdd = this.data.canUseListAdd;
		if (this.data.checkedAll) {
			for(let i = 0; i < canUseList.length; i++){
				if (canUseList[i].check) {
					canUseList[i].check = false
				} 
			}
			for(let i = 0; i < canUseListAdd.length; i++){
				if (canUseListAdd[i].check) {
					canUseListAdd[i].check = false
				} 
			}
			this.setData({
				checkedAll: false
			})
		} else {
			for(let i = 0; i < canUseList.length; i++){
				if (!canUseList[i].check) {
					canUseList[i].check = true
				} 
			}
			for(let i = 0; i < canUseListAdd.length; i++){
				if (!canUseListAdd[i].check) {
					canUseListAdd[i].check = true
				} 
			}
			this.setData({
				checkedAll: true
			})
		}

		this.setData({
			canUseList: canUseList,
			canUseListAdd: canUseListAdd
		})
	},

	//选择档案编号
	selectCurrent(e) {
		let carArchivesNbr = e.detail.carArchivesNbr,
			canUseList = this.data.canUseList,
			isCheckedAll = true;
			
		for (let i = 0; i < canUseList.length; i++) {
			if (carArchivesNbr == canUseList[i].carArchivesNbr) {
				canUseList[i].check = !canUseList[i].check
			}
		}
		for (let j = 0; j < canUseList.length; j++) {
			if (!canUseList[j].check) {
				isCheckedAll = false
			} 
		}
		this.setData({
			canUseList: canUseList,
			checkedAll: isCheckedAll
		})
	},
	
	//点击导航切换
	handleIndexChange(e) {
		this.setData({
			tagAction: e.detail.active
		})
	},

	onShow() {
		if (app.getStorageSync(app.globalData.paySuccessSign)) { //从支付成功页返回，跳回首页
			wx.navigateBack();
		}
		let page = app.getStorageSync(app.globalData.cacheAddress);
		if (page) {
			this.setData({
				name: page.name,
				phone: page.phone,
				area: page.area,
				street: page.street,
				address: page.address
			})
		}
	},
	cacheSign() {
        app.removeStorageSync(app.globalData.paySuccessSign)
		app.setStorageSync(app.globalData.cacheAddress, this.data)
	},
	onHide() {
		this.cacheSign()
	},
	onUnload() {
		this.cacheSign()
	},
    onLoad(options) {
		// canUseList
		//noUseList 不可
		let carList = app.getStorageSync(app.globalData.cachePayMnet),
			canUseList = carList.canUseList, //可预期
			noUseList = carList.noUseList, //不可预期
			formResult = carList.formResult; //提交的数据
			// console.log(formResult)
			console.log('上个页面缓存',carList)
				let aloneCanUseList = [],
					aloneCanText = '',
					isAloneCanUseList = false,
					isShowAddress = true;
			if (!canUseList.length || !noUseList.length) {
				if (canUseList.length) {
					aloneCanUseList = canUseList
					aloneCanText = '可延期车辆' //一种情况下的文案
				} else {
					aloneCanUseList = noUseList
					aloneCanText = '不可延期车辆' //一种情况下的文案
					isShowAddress = false  
				}
				isAloneCanUseList = true  //只有一种可选的情况
			}
		this.setData({
			isShowAddress: isShowAddress,
			isAloneCanUseList: isAloneCanUseList,
			aloneCanText: aloneCanText,
			aloneCanUseList: aloneCanUseList,
			checkedAll: true,
			directType: formResult.directType, //办理类型
			inlandTelNbr: formResult.inlandTelNbr, //内地手机号

			fileNbr: formResult.fileNbr || '', //卷宗号
			witnessName: formResult.witnessName || '', //办证员姓名
			cardNbr: formResult.cardNbr || '',  //身份证号码

			carArchivesNbr: formResult.carArchivesNbr || '', //车辆档案号
			inlandCarNbr: formResult.inlandCarNbr || '', //车牌号
			frameLastSix: formResult.frameLastSix || '', //车架号

			directTitle: '卷宗号', //提交的类型
			fileNbr: formResult.fileNbr
		})	
			
		for (let i = 0; i < canUseList.length; i++) {
			canUseList[i]['check'] = true
		}
		if (canUseList.length > 3) { //可预期
			this.setData({
				addMore: false, //显示 更多文案
				isShowAddMore: true, //隐藏按钮
				canUseList: canUseList.slice(0,3),  //如果列表长度大于3，先显示3个
				canUseListAdd: canUseList.slice(3)
			})
		} else {
			this.setData({
				canUseList: canUseList,
				isShowAddMore: false //隐藏按钮
			})
		}

		if (noUseList.length > 3) {
			this.setData({
				noUseList: noUseList.slice(0,3),  //如果列表长度大于3，先显示3个
				noUseListAdd: noUseList.slice(3),
				isShowAddMoreMustNot: true //隐藏按钮

			})
		} else {
			this.setData({
				noUseList: noUseList,
				isShowAddMoreMustNot: false //隐藏按钮
			})
		}
		app.initAddress();
	},

	onUnload() {
		// app.removeStorageSync(app.globalData.cacheData);
	},
	
	toBack() {
		wx.navigateBack();
	},
});
